package SGUI

import (
	. "SGEngine2"
	"dom4g"
	"fmt"
	"github.com/gl"
	"strconv"
)

func GenRectangeByXML(elem *dom4g.Element, node *Node, tw *TopWidget, p IWidget) IWidget {
	newWidget := &Rectange{}
	newWidget.Node = node
	newWidget.Top = tw
	newWidget.Node.Scale = VecOne
	if v, ok := elem.AttrValue("Color"); ok {
		if v[0] == '#' {
			r, _ := strconv.ParseInt(v[1:3], 16, 32)
			g, _ := strconv.ParseInt(v[3:5], 16, 32)
			b, _ := strconv.ParseInt(v[5:7], 16, 32)
			var a int64
			a = 255
			if len(v) > 7 {
				var err error
				a, err = strconv.ParseInt(v[7:9], 16, 32)
				if err != nil {
					fmt.Println(err)
				}
			}
			newWidget.Color = NewColor4Byte(float32(r), float32(g), float32(b), float32(a))
		}
	}
	parseNodeAttrs(elem, newWidget, p)

	return newWidget
}

type Rectange struct {
	WidgetInfo
	Color Color4
}

func (r *Rectange) GetWidgetInfo() *WidgetInfo {
	return &r.WidgetInfo
}

func (this *Rectange) OnEnable(node *Node) {
	this.Component2D.OnAttach(node)
	node.GetRender().Mat = this.GenMaterial()
	node.GetRender().RenderMesh = this.Component2D.GenQuadMesh(&this.Color, false)
}

func (this *Rectange) OnDisable(node *Node) {
	node.GetRender().RenderMesh.Destory()
	node.SetRender(nil)

}

func (this *Rectange) OnReSize() {
	x, y := this.GetSize()
	this.Width = x
	this.Height = y
	this.SetSize(x, y)
}

func (r *Rectange) OnUpdate() {

}
func (r *Rectange) OnAttach(node *Node) {

}

func (this *Rectange) OnLoad() {

}

func (rect *Rectange) SetColorRGBA(r, g, b, a float32) {
	rect.Color.R = r
	rect.Color.G = g
	rect.Color.B = b
	rect.Color.A = a

	mesh := rect.WidgetInfo.Node.GetRender().RenderMesh
	mesh.Color = []float32{
		rect.Color.R, rect.Color.G, rect.Color.B, rect.Color.A,
		rect.Color.R, rect.Color.G, rect.Color.B, rect.Color.A,
		rect.Color.R, rect.Color.G, rect.Color.B, rect.Color.A,
		rect.Color.R, rect.Color.G, rect.Color.B, rect.Color.A,
	}
	mesh.Colorbuffer.Bind(gl.ARRAY_BUFFER)
	gl.BufferSubData(gl.ARRAY_BUFFER, 0, 16*4, mesh.Color)
}

func (this *Rectange) SetSize(w, h float32) {
	if this.Node.Active() == false {
		return
	}
	this.Width = w
	this.Height = h
	mesh := this.Node.GetRender().RenderMesh
	mesh.Bounds, mesh.Vertices = this.GenQuadVerticeMesh()
	mesh.Vertbuffer.Bind(gl.ARRAY_BUFFER)
	gl.BufferSubData(gl.ARRAY_BUFFER, 0, 12*4, mesh.Vertices)
}

func (r *Rectange) GenMaterial() *Material {
	mat := new(Material)
	mat.Shader = ShaderManager.SahderGet("Rectange")
	if r.Color.A == 1 {
		mat.IsTrans = false
	} else {
		mat.IsTrans = true
	}

	return mat
}
